package com.robot.orders.handler.pay;

import com.github.wxpay.sdk.WeChatPay;
import com.github.wxpay.sdk.WeChatPayUtil;
import com.robot.orders.config.WeChatPayConfig;
import com.robot.orders.handler.AbstractHandler;
import com.robot.orders.handler.HandlerType;
import com.robot.orders.pojo.vo.OrdersRequestModel;
import com.robot.orders.pojo.vo.Payment;
import entity.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: CipherCui
 * @Description: 促销订单处理器
 * @Date: Created in 10:17 2019/2/2
 */
@Component
@HandlerType(Constant.WE_CHAT_NATIVE_PAY)
public class WeChatNativePayHandler extends AbstractHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public HashMap<String,String> handle(Payment payment , OrdersRequestModel ordersRequestModel) throws Exception {

        WeChatPayConfig config = new WeChatPayConfig();
        WeChatPay weChatPay = new WeChatPay(config);
        HashMap<String, String> result = new HashMap<>();

        try {
            Map<String, String> req = new HashMap<>(10);

            req.put("appid", config.getAppId());
            req.put("mch_id", config.getMchId());
            req.put("nonce_str", String.valueOf(System.currentTimeMillis()));
            req.put("body", "付款");
            req.put("out_trade_no", ordersRequestModel.getOrdersId());
            BigDecimal cent = new BigDecimal(100);
            req.put("total_fee", ordersRequestModel.getPayAmount().multiply(cent).stripTrailingZeros().toPlainString());
            req.put("spbill_create_ip", ordersRequestModel.getRequestIp());
            req.put("notify_url", config.getRedirectUri());
            req.put("openid", ordersRequestModel.getOpenId());
            req.put("trade_type", "JSAPI");

            Map<String, String> response = weChatPay.unifiedOrder(req);
            logger.info(response.toString());
            if ("SUCCESS".equals(response.get("result_code"))) {
                result.put("timestamp", String.valueOf(System.currentTimeMillis()));
                result.put("signType", "MD5");
                result.put("package", "prepay_id="+response.get("prepay_id"));
                result.put("nonceStr",String.valueOf(System.currentTimeMillis()));
                result.put("paySign", WeChatPayUtil.generateSignature(result, config.getKey()));
            } else {
                result.put("error", response.get("err_code"));
                result.put("msg", response.get("err_code_des"));
            }

        } catch (Exception e) {
            logger.info("exception");
            logger.info(e.getStackTrace().toString());
            logger.info(e.getMessage());
        }


        return result;
    }

}
